// 客户端
import {getCache, setCache, setTempCache, getTempCache} from '../../utils/localStorage.js'

const user = {
	state: {
  	token: null,				// 令牌
  	readRecords: [],		// 阅读记录
  	collectRecords: []  // 收藏记录
  },
	mutations: {
		'SET_TOKEN': (state, newToken) => {
			state.token = newTest
		},
		'SET_READ_RECORDS': (state, newVal) => {
			state.readRecords = newVal
		},
		'SET_COLLECT_RECORDS': (state, newVal) => {
			state.collectRecords = newVal
		}
	},
	actions: {
		setToken: ({commit, state}, newToken) => {
			return commit('SET_TOKEN',newToken)
		},
		setReadRecords: ({commit, state}, newVal) => {
			// TODO 应该向服务器提交数据
			// newVal 是 obj == {"cid": 1, "sid": "123"}
			if (!newVal) { return }
			let _readRecords = getCache('readRecords')
			if (!_readRecords){
				_readRecords = []
			}
			try {
				let _keys = _readRecords.map(item=>item.cid)
				if (_keys.includes(newVal.cid)) {
					// 记录存在则更新记录
					const _index = _keys.findIndex(item=>item==newVal.cid)
					_readRecords[_index].sid = newVal.sid
				}else{
					_readRecords.unshift(newVal)
				}
			}catch(e) {
				console.log(e)
			}
			setCache('readRecords', [...new Set(_readRecords)])
			return commit('SET_READ_RECORDS', _readRecords)
		},
		setCollectRecords: ({commit, state}, newVal) => {
			// TODO 应该向服务器提交数据
			// 收藏
			// newVal 是 obj {"cid": 1}
			// 记录存在 返回
			let _collectRecords = getTempCache('collectRecords')
			if (!_collectRecords) { _collectRecords = [] }
			const has = _collectRecords.inludes(newVal)
			if (has) { return }
			_collectRecords.push(newVal)
			setTempCache('collectRecords', [...new Set(_collectRecords)])
			return commit('SET_COLLECT_RECORDS', _collectRecords)
		},
		unSetCollectRecords: ({commit, state}, newVal) => {
			// TODO 应该向服务器提交数据
			// 取消收藏
			// newVal 是 obj 
			// 记录不存在 返回
			let _collectRecords = getTempCache('collectRecords')
			if (!_collectRecords) { _collectRecords = [] }
			const has = _collectRecords.inludes(newVal)
			if (!has) { return }
			_collectRecords.pop(newVal)
			setTempCache('collectRecords', _collectRecords)
			return commit('SET_COLLECT_RECORDS', _collectRecords)
		}
	}
}

export default user
